package com.comp3111.happymeal;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.configuration.Configuration;
import com.controller.MealFetch;
import com.controller.RestaurantFetch;
import com.object.Meal;

import android.app.Activity;
import android.app.SearchManager;//Ryan: Just Added
import android.content.Context;//Ryan: Just Added
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu; //Ryan: Just Added
import android.view.MenuInflater; //Ryan: Just Added
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;//Ryan: Just Added
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;

public class SearchActivity extends NavigationDrawerActivity {
    private List<Integer> mealIdList;	//Id for the food list for that restaurant
    Drawable tmpPicture;
    String mealPictureDrawableURL;
	private ListView mealListView;
	private SimpleAdapter mealAdapter;
	
	private static ImageView searchBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_using_listview_only);

        createDrawer();
//        startSearch();
	    handleIntent(getIntent());

//        searchBtn = (ImageView) findViewById(R.id.search_button);
//        searchBtn.setOnClickListener(new ImageView.OnClickListener() {
//			public void onClick(View v) {
//				Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
//			    startActivity(intent);
//			}
//		});
    }
	
	@Override
	protected void onNewIntent(Intent intent) {
        setContentView(R.layout.page_using_listview_only);
	    handleIntent(intent);
	}
	private void handleIntent(Intent intent) {
//ADD:
        
	    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
	        String query = intent.getStringExtra(SearchManager.QUERY);
			Log.d("Query", query);
	        //ADD--
			
	        setContentView(R.layout.page_using_listview_only);
	        createDrawer();


        mealListView = (ListView)findViewById(R.id.page_using_listview_only_listview);
        mealAdapter = new SimpleAdapter(this,getMealListView(query),R.layout.food_list,
        		new String[]{"food_pic","food_name","restaurant_name", "love", "price"},
				new int[]{R.id.food_list_picture, R.id.food_name, R.id.restaurant_name, R.id.love, R.id.price});
      
        
        
        mealListView.setAdapter(mealAdapter);
        mealAdapter.setViewBinder(new ViewBinder(){
        	public boolean setViewValue(View view,Object data,String textRepresentation){
				if(view instanceof ImageView && data instanceof Drawable){
					ImageView iv=(ImageView)view;
					iv.setImageDrawable((Drawable)data);
					return true;
				}
				else return false;
			}
        });
        
        mealListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
            	int mealId = mealIdList.get(position);
                //Toast.makeText(DiscoverPageActivity.this,"ID���G" + Integer.toString(mealId) ,Toast.LENGTH_SHORT).show();
                
                //Jump to FoodFoodPageActivity
                Intent intentPass = new Intent(SearchActivity.this, FoodPageActivity.class);
				
				//Pass pass intent								
				intentPass.putExtra("MEALID",Integer.toString(mealId).trim());
					
				//Go to next page
				startActivity(intentPass);

            }
        });
    
        //Release unused ram
        System.gc();
               //---END
	        //use the query to search your data somehow
//	        doSearch(query);
	    }
	}
		
	  /*
     * List containing the list of food of that restaurant
     */
    private List<Map<String, Object>> getMealListView(String inputName) {
    	
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		mealIdList = new ArrayList<Integer>();
		
		MealFetch mealFetch = new MealFetch();
		RestaurantFetch restaurantFetch = new RestaurantFetch();

		List<Meal> mealList = mealFetch.searchMeal(inputName);
	    //List<Restaurant> restaurantList = restaurantFetch.fetchAllRestaurant();
	    if(mealList==null){
	    	Log.d("Query", "mealLst does not exist!");
	    }
	    if(mealList != null){
//	    	int counter = 0;
		    for(Meal meal : mealList){
//		    	if(counter > 4){
////		    		?
//		    		break;
//		    	}else{
//		    		counter++;
//		    	}
				Log.d("Query", "I am here!3");

				Map<String, Object> map = new HashMap<String, Object>();
				
				if(meal.getPicture()!=null){
					
					mealPictureDrawableURL = Configuration.baseURL + meal.getPicture();
					
					//Start a new thread and use POST method to send telephone and passcode to authURL
			        //Start a new thread to attempt Login (requirement when connecting online)
					Thread attemptThread = new Thread(new Runnable(){  
						public void run(){  
							tmpPicture = loadImageFromURL(mealPictureDrawableURL);		
						}
					});  
					attemptThread.start();
					
					while(attemptThread.isAlive()){
						//Wait for server response
					}
				}
				Log.d("Query", "I am here!4");

				map.put("food_pic", tmpPicture);
				map.put("food_name", meal.getName());
				int id = meal.getRestaurant();
				map.put("restaurant_name", restaurantFetch.fetchRestaurantNameById(id));
				map.put("love", Integer.toString(mealFetch.fetchMealLikeById(meal.getId())) + " loves");
				map.put("price", "$" + meal.getPrice());
				Log.d("Query","test");
				
				list.add(map);
				mealIdList.add(meal.getId());
				
	    	}
	    }

		return list;
	}
    
    private Drawable loadImageFromURL(String url){
        try{
        	InputStream is = (InputStream) new URL(url).getContent();
            Bitmap tmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeStream(is),Configuration.THUMBSIZE,Configuration.THUMBSIZE);
            return new BitmapDrawable(getResources(), tmp);
        	/*
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable draw = Drawable.createFromStream(is, "src");
            return draw;
            */
        }catch (Exception e) {
            //TODO handle error
            Log.i("loadingImg", e.toString());
            return null;
        }
    }
    
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        // Associate searchable configuration with the SearchView
        SearchManager searchManager =
               (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));        
        return true;
    }

}